package com.ruoyi.system.service.impl;

import java.util.List;

import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.EnterpriseInfoVO;
import com.ruoyi.system.dto.AliyunSmsDTO;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IGwEnterpriseInfoService;
import com.ruoyi.system.utils.SendSmsUtil;
import com.ruoyi.system.utils.WeChatUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.IGwNoticeService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 通知公告Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-29
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class GwNoticeServiceImpl implements IGwNoticeService {

    @Resource
    private GwNoticeMapper gwNoticeMapper;
    @Resource
    private GwStaffMapper gwStaffMapper;
    @Resource
    private GwNoticeFileMapper gwNoticeFileMapper;
    @Resource
    private GwNoticeStaffMapper gwNoticeStaffMapper;
    @Resource
    private SendSmsUtil sendSmsUtil;
    @Resource
    private WeChatUtil weChatUtil;
    @Resource
    private IGwEnterpriseInfoService gwEnterpriseInfoService;
    @Resource
    private GwEnterpriseInfoMapper gwEnterpriseInfoMapper;
    /**
     * 查询通知公告
     *
     * @param id 通知公告主键
     * @return 通知公告
     */
    @Override
    public GwNotice selectGwNoticeById(String id) {
        GwNotice gwNotice = gwNoticeMapper.selectGwNoticeById(id);
        //文件信息
        GwNoticeFile queryFile = new GwNoticeFile();
        queryFile.setNoticeId(id);
        List<GwNoticeFile> gwNoticeFiles = gwNoticeFileMapper.selectGwNoticeFileList(queryFile);
        gwNotice.setGwNoticeFileList(gwNoticeFiles);
        //员工信息
        GwNoticeStaff queryStaff = new GwNoticeStaff();
        queryStaff.setNoticeId(id);
        List<GwNoticeStaff> gwNoticeStaffs = gwNoticeStaffMapper.selectGwNoticeStaffList(queryStaff);
        gwNotice.setGwNoticeStaffList(gwNoticeStaffs);
        return gwNotice;
    }

    /**
     * 查询通知公告列表
     *
     * @param gwNotice 通知公告
     * @return 通知公告
     */
    @Override
    public List<GwNotice> selectGwNoticeList(GwNotice gwNotice) {
        //设置公司ID
        System.out.println("-----applet login enterpriseId:"+SecurityUtils.getLoginUser().getEnterpriseId()+"-------------------");
        String companyId = ObjectUtils.isNotEmpty(SecurityUtils.getLoginUser().getEnterpriseId()) ? SecurityUtils.getLoginUser().getEnterpriseId() : "-1";
        gwNotice.setCompanyId(companyId);
        //企业管理员看公司的
        if(!"1".equals(SecurityUtils.getLoginUser().getUser().getUserType())){
            //其他人看自己创建的
            gwNotice.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        }
        return gwNoticeMapper.selectGwNoticeList(gwNotice);
    }

    /**
     * 新增通知公告
     *
     * @param gwNotice 通知公告
     * @return 结果
     */
    @Override
    public int insertGwNotice(GwNotice gwNotice) throws ClientException, WxErrorException {
        // 判断短信数量是否够用
        EnterpriseInfoVO myEnterpriseInfo = gwEnterpriseInfoMapper.getLoginEnterpriseInfo(SecurityUtils.getLoginUser().getEnterpriseId());
        if (ObjectUtils.isEmpty(myEnterpriseInfo)) {
            throw new GlobalException("未知的公司，操作失败!!!");
        }

        if(myEnterpriseInfo.getSmsSurplusNum() < gwNotice.getGwNoticeStaffList().size()){
            throw new GlobalException("当前短信条数余额不足，操作失败!!!");
        }

        // 设置公司ID
        if(ObjectUtils.isEmpty(SecurityUtils.getLoginUser().getEnterpriseId())){
            throw new GlobalException("未知的公司,请绑定公司再进行操作");
        }
        gwNotice.setCompanyId(SecurityUtils.getLoginUser().getEnterpriseId());
        //gwNotice.setId(IdUtils.fastSimpleUUID());
        gwNotice.setCreateTime(DateUtils.getNowDate());
        gwNotice.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        gwNotice.setUpdateTime(DateUtils.getNowDate());
        gwNotice.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        gwNoticeMapper.insertGwNotice(gwNotice);
        if (ObjectUtils.isNotEmpty(gwNotice.getGwNoticeFileList())) {
            for (GwNoticeFile gwNoticeFile : gwNotice.getGwNoticeFileList()) {
                gwNoticeFile.setId(IdUtils.fastSimpleUUID());
                gwNoticeFile.setNoticeId(gwNotice.getId() + "");
                gwNoticeFile.setCreateTime(DateUtils.getNowDate());
                gwNoticeFile.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
                gwNoticeFile.setUpdateTime(DateUtils.getNowDate());
                gwNoticeFile.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
                gwNoticeFileMapper.insertGwNoticeFile(gwNoticeFile);
            }
        }
        addStaffAction(gwNotice.getGwNoticeStaffList(), gwNotice, myEnterpriseInfo);
        return 1;
    }

    public void addStaffAction(List<GwNoticeStaff> getGwNoticeStaffList, GwNotice gwNotice, EnterpriseInfoVO myEnterpriseInfo) throws ClientException, WxErrorException {
        for (GwNoticeStaff gwNoticeStaff : getGwNoticeStaffList) {
            gwNoticeStaff.setId(IdUtils.fastSimpleUUID());
            gwNoticeStaff.setNoticeId(gwNotice.getId() + "");
            gwNoticeStaff.setCreateTime(DateUtils.getNowDate());
            gwNoticeStaff.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            gwNoticeStaff.setUpdateTime(DateUtils.getNowDate());
            gwNoticeStaff.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            gwNoticeStaffMapper.insertGwNoticeStaff(gwNoticeStaff);

            //发送短信
            //【Gowork】[企业名称]发布[标题]的通知，请查阅。[通知通告的H5链接]
            GwStaff gwStaff = gwStaffMapper.selectGwStaffById(gwNoticeStaff.getStaffId());
            if (ObjectUtils.isNotEmpty(gwStaff) && ObjectUtils.isNotEmpty(gwStaff.getTel())) {
                // 获取小程序链接
                //String urlLink = weChatUtil.generateUrlLink("/other/gwnotice/gwnoticeForm", "id=" + gwNoticeStaff.getId() +"&userId=" + gwNoticeStaff.getId());

                AliyunSmsDTO aliyunSmsDTO = new AliyunSmsDTO();
                aliyunSmsDTO.setPhoneNumbers(gwStaff.getTel());
                aliyunSmsDTO.setTemplateCode("SMS_490520080");
                JSONObject json = new JSONObject();
                // 设置模板参数
                json.put("company", myEnterpriseInfo.getEnterpriseName());
                json.put("title", gwNotice.getTitle());
                json.put("noticeId", gwNotice.getId());
                json.put("userId", gwStaff.getId());
                aliyunSmsDTO.setTemplateParam(json.toJSONString());
                sendSmsUtil.sendSms(aliyunSmsDTO);
            }
        }
        
        //增加短信数
        myEnterpriseInfo = gwEnterpriseInfoMapper.getLoginEnterpriseInfo(SecurityUtils.getLoginUser().getEnterpriseId());
        GwEnterpriseInfo enterpriseInfo = new GwEnterpriseInfo();
        enterpriseInfo.setId(myEnterpriseInfo.getId());
        enterpriseInfo.setSmsUseNum(myEnterpriseInfo.getSmsUseNum() + getGwNoticeStaffList.size());
        gwEnterpriseInfoMapper.updateGwEnterpriseInfo(enterpriseInfo);
    }

    @Override
    public int addStaff(GwNotice gwNotice) throws ClientException, WxErrorException {
        // 判断短信数量是否够用
        EnterpriseInfoVO myEnterpriseInfo = gwEnterpriseInfoMapper.getLoginEnterpriseInfo(SecurityUtils.getLoginUser().getEnterpriseId());

        if(ObjectUtils.isEmpty(myEnterpriseInfo)){
            throw new GlobalException("未知的公司，操作失败!!!");
        }
        if(myEnterpriseInfo.getSmsSurplusNum() < gwNotice.getGwNoticeStaffList().size()){
            throw new GlobalException("当前短信条数余额不足，操作失败!!!");
        }
        addStaffAction(gwNotice.getGwNoticeStaffList(), gwNotice, myEnterpriseInfo);
        return gwNotice.getGwNoticeStaffList().size();
    }

    @Override
    public int setRead(GwNotice gwNotice) {
        gwNoticeStaffMapper.setReadByNoticeIdAndStaffId(gwNotice.getId()+"", gwNotice.getUserId());
        return 1;
    }

    /**
     * 修改通知公告
     *
     * @param gwNotice 通知公告
     * @return 结果
     */
    @Override
    public int updateGwNotice(GwNotice gwNotice) {
        gwNotice.setUpdateTime(DateUtils.getNowDate());
        gwNotice.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        return gwNoticeMapper.updateGwNotice(gwNotice);
    }

    /**
     * 批量删除通知公告
     *
     * @param ids 需要删除的通知公告主键
     * @return 结果
     */
    @Override
    public int deleteGwNoticeByIds(String[] ids) {
        for (String id : ids) {
            gwNoticeFileMapper.deleteGwNoticeFileByMainId(id);
            gwNoticeStaffMapper.deleteGwNoticeStaffByMainId(id);
        }
        return gwNoticeMapper.deleteGwNoticeByIds(ids);
    }

    /**
     * 删除通知公告信息
     *
     * @param id 通知公告主键
     * @return 结果
     */
    @Override
    public int deleteGwNoticeById(String id) {
        return gwNoticeMapper.deleteGwNoticeById(id);
    }

}
